package com.phonemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;
import com.phonemap.models.Position;

/**
 * 
 * @author Administrator
 * 
 */
@SuppressWarnings("serial")
public class PositionServlet extends BaseServlet {
	private static final Logger logger = Logger.getLogger(PositionServlet.class
			.getCanonicalName());

	/**
	 * Get the requested position entities in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining Position listing");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = null;
		if (searchFor == null || searchFor.equals("")) {
			entities = Position.getAllPositions();
			out.println(Util.writeJSON(entities));
		} else {
			entities = Position.getPosition(searchFor);
			out.println(Util.writeJSON(entities));
		}
		return;
	}

	/**
	 * Insert the new position
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating Position");
		String userId = req.getParameter("user");
		Double latitude = Double.parseDouble(req.getParameter("latitude"));
		Double longitude = Double.parseDouble(req.getParameter("longitude"));
		Position.createOrUpdatePosition(userId, latitude, longitude);
	}

	/**
	 * Delete the position
	 */
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Deleting order from the listing");
		String positionId = req.getParameter("id");
		String phone = req.getParameter("parentid");

		Key parentKey = KeyFactory.createKey("User", phone);
		Key key = KeyFactory.createKey(parentKey, "Position",
				Integer.parseInt(positionId));
		Util.deleteEntity(key);
	}

	/**
	 * Redirect the call to doDelete or doPut method
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}
}
